import 'package:flutter/material.dart';
import 'package:ebook/base/Util.dart';
import 'package:flutter_tts/flutter_tts.dart';
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart' show kIsWeb;

class Read extends StatefulWidget {
  const Read({Key? key, required this.data}) : super(key: key);
  final Map<String, dynamic> data;
  @override
  _ReadState createState() => _ReadState();
}

class _ReadState extends State<Read> {
  var page = 0;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initTts();
  }

  @override
  void dispose() {
    super.dispose();
    flutterTts.stop();
  }

  initTts() {
    flutterTts = FlutterTts();

    _setAwaitOptions();
    if (isAndroid) {
      _getDefaultEngine();
    }

    flutterTts.setStartHandler(() {
      setState(() {
        print("Playing");
        ttsState = TtsState.playing;
      });
    });

    flutterTts.setCompletionHandler(() {
      setState(() {
        print("Complete");
        ttsState = TtsState.stopped;
      });
    });

    flutterTts.setCancelHandler(() {
      setState(() {
        print("Cancel");
        ttsState = TtsState.stopped;
      });
    });

    if (isWeb || isIOS || isWindows) {
      flutterTts.setPauseHandler(() {
        setState(() {
          print("Paused");
          ttsState = TtsState.paused;
        });
      });

      flutterTts.setContinueHandler(() {
        setState(() {
          print("Continued");
          ttsState = TtsState.continued;
        });
      });
    }

    flutterTts.setErrorHandler((msg) {
      setState(() {
        print("error: $msg");
        ttsState = TtsState.stopped;
      });
    });
  }

  Future _getDefaultEngine() async {
    var engine = await flutterTts.getDefaultEngine;
    if (engine != null) {
      print(engine);
    }
  }

  Future _setAwaitOptions() async {
    await flutterTts.awaitSpeakCompletion(true);
  }

  void startRead() async {
    flutterTts.setLanguage('zh-CN');
    double volume = 0.5;
    double pitch = 1.0;
    double rate = 0.9;
    await flutterTts.setVolume(volume);
    await flutterTts.setSpeechRate(rate);
    await flutterTts.setPitch(pitch);
    if (ttsState == TtsState.playing) {
      await flutterTts.stop();
    } else {
      await flutterTts.speak(widget.data["text"][page].toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.data["name"].toString()),
        actions: [
          Container(
            color: Colors.greenAccent,
            child: TextButton(
                onPressed: () => {startRead()}, child: const Text("read")),
          )
        ],
      ),
      body: Container(
          padding: const EdgeInsets.all(5),
          child: TextButton(
            child: Text(
              widget.data["text"][page].toString(),
              style: Util.smallBlack,
            ),
            onPressed: () {
              setState(() {
                if (page < widget.data["text"].length - 1) {
                  page++;
                }
              });
            },
          )),
    );
  }

  late FlutterTts flutterTts;
  TtsState ttsState = TtsState.stopped;
  bool get isIOS => !kIsWeb && Platform.isIOS;
  bool get isAndroid => !kIsWeb && Platform.isAndroid;
  bool get isWindows => !kIsWeb && Platform.isWindows;
  bool get isWeb => kIsWeb;
}

enum TtsState { playing, stopped, paused, continued }
